<!-- 农机手入驻申请 -->
<template>
	<view style="width: 100%;height: 100%;">
		<uni-nav-bar title="农机手入驻申请" @clickLeft="back" left-icon="left" backgroundColor="#fff" color="#000"
			statusBar="true">
		</uni-nav-bar>
		<view v-if="true">
			<u-form labelPosition="left" :model="model" :rules="rules" ref="form">
				<!-- 0.入驻运营方 -->
				<u-form-item label="入驻运营方" prop="formData.operatorName" borderBottom
					@click="showOperate = true;hideKeyboard()">
					<view class="left-image" >
						<image class="left-img" src="@/subPage1/static/service/huodongyunying.png" mode="heightFix"></image>
					</view>
					<picker mode=selector @cancel="selectOperatorClose" @change="selectOperator" range-key="name" :value="model.formData.operatorName"
						:range="operatorList">
						<u--input v-model="model.formData.operatorName" style="pointer-events: none" disabled
							disabledColor="#ffffff" placeholder="请选择运营方" border="none"></u--input>
						<u-icon name="arrow-down"></u-icon>
					</picker>
				</u-form-item>
				<!-- 0.1服务方 -->
				<u-form-item label="服务方" v-show="model.formData.serviceProviderNo" prop="formData.organizationName" borderBottom>
					<!-- style="background: linear-gradient(180deg, #57DED9 0%, #2291FF 100%);" -->
					<view class="left-image">
						<image class="left-img" src="@/subPage1/static/service/fuwufang.png" mode="heightFix"></image>
					</view>
					<picker mode=selector @cancel="selectOrganizationClose" @change="selectOrganization" range-key="name" :value="model.formData.organizationName"
						:range="organizationList">
						<u--input v-model="model.formData.organizationName" style="pointer-events: none" disabled
							disabledColor="#ffffff" placeholder="请选择入驻运营方" border="none"></u--input>
						<u-icon name="arrow-down"></u-icon>
					</picker>
				</u-form-item>
				<!-- 1.姓名 -->
				<u-form-item label="姓名" prop="formData.name">
					<view class="left-image">
						<image class="left-img" src="@/subPage1/static/machinery/xingming.png" mode="heightFix"></image>
					</view>
					<u--input v-model="model.formData.name" placeholder='请输入姓名' border="none"></u--input>
				</u-form-item>
				<!-- 2.驾龄 -->
				<u-form-item label="驾龄" prop="formData.driveAge">
					<view class="left-image">
						<image class="left-img" src="@/subPage1/static/machinery/jiashicang.png" mode="heightFix"></image>
					</view>
					<u--input v-model="model.formData.driveAge" placeholder='请输入驾龄' type="number"
						border="none"></u--input>
				</u-form-item>
				<!-- 3.联系电话 -->
				<u-form-item label="联系电话" prop="formData.phone">
					<view class="left-image">
						<image class="left-img" src="@/subPage1/static/machinery/lianxidianhua.png" mode="heightFix"></image>
					</view>
					<u--input v-model="model.formData.phone" placeholder='请输入联系电话' type="number"
						border="none"></u--input>
				</u-form-item>
				<!-- 4.驾驶证照片  -->
				<u-form-item label="驾驶证照片" prop="formData.imgList"  >
					<view class="left-image">
						<image class="left-img" src="@/subPage1/static/machinery/yingyezhizhao.png" mode="heightFix"></image>
					</view>
					<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						deletable :maxCount="1">点击上传</u-upload>
				</u-form-item>
				<!-- 5.行驶证照片  -->
				<u-form-item  label="行驶证照片" prop="formData.imgList1" >
					<view class="left-image">
						<image class="left-img" src="@/subPage1/static/machinery/tuwenxiangqing.png" mode="heightFix"></image>
					</view>
					<u-upload :fileList="fileList1" @afterRead="afterRead1" @delete="deletePic1" name="1" multiple
						deletable :maxCount="1">点击上传</u-upload>
				</u-form-item>
				<!-- 6.身份证 -->
				<u-form-item label="身份证" prop="formData.imgList2" style="background-color: #E2E7F8;">
					<view class="left-image">
						<image class="left-img" src="@/subPage1/static/service/yingyezhizhao.png" mode="heightFix"></image>
					</view>
					<u-upload :fileList="fileList2" @afterRead="afterRead2" @delete="deletePic2" name="1" multiple
						deletable :maxCount="2">
						<view class="uploadBtns">
							<view v-if="fileList2.length < 1">
								上传正面
							</view>
							<view style="margin-left: 30rpx;" v-if="fileList2.length < 2">
								上传反面
							</view>
						</view>
					</u-upload>
				</u-form-item>
			</u-form>
			<!-- 提交 -->
			<view class="submit">
				<button @click="application()" class="submit-btn">
					<text>提交申请入驻</text>
				</button>
			</view>
		</view>
		<view class="blank" v-else>
			<image src="@/static/blank.png" mode="heightFix"></image>
			<view class="title">
				您近期已申请过入驻，您可以在消息功能中留意入驻申请结果。
			</view>
		</view>
	</view>
</template>

<script>
	import API from '@/api/socialized-servce/farm-service/person-message/mechanist-application/index.js'
	import agriculturalApi from '@/api/socialized-servce/agricultural-information/index.js'
	import {
		socializedBaseurl
	} from '@/config/baseUrl.js'
	export default {
		data() {
			return {
				showOperate: false,
				operatorList: [{
						name: '吴兴',
						id: 1
					},
					{
						name: '大龙',
						id: 2
					}
				],
				organizationList: [],
				fileList: [],
				fileList1: [],
				fileList2: [],
				model: {
					formData: {
						userId: uni.getStorageSync('userId'),
						operatorName: '',
						serviceProviderNo: '',
						organizationName: '',
						organizationNo: '',
						name: '',
						driveAge: '',
						phone: '',
						imgList: [],
						imgList1: [],
						imgList2: []
					}
				},
				rules: {
					'formData.operatorName': {
						type: 'string',
						required: true,
						message: '请选择入驻运营方',
						trigger: ['blur', 'change']
					},
					'formData.organizationName': {
						type: 'string',
						required: true,
						message: '请选择入服务方',
						trigger: ['blur', 'change']
					},
					'formData.name': {
						type: 'string',
						required: true,
						message: '姓名不能为空',
						trigger: ['blur', 'change']
					},
					'formData.driveAge': {
						type: 'string',
						required: true,
						message: '驾龄不能为空',
						trigger: ['blur', 'change']
					},
					'formData.phone': [{
							type: 'string',
							required: true,
							message: '联系电话不能为空',
							trigger: ['blur', 'change']
						},
						{
							type: 'string',
							validator: (rule, value, callback) => {
								if (value.length <= 11) {
									if (value != '') {
										return this.$u.test.mobile(value)
									}
								} else {
									return false
								}
							},
							message: '手机号格式不对,请输入正确的手机号',
							trigger: ['blur', 'change']
						}
					],
					'formData.imgList': {
						type: 'array',
						required: true,
						message: '请上传驾驶证照片',
						trigger: ['blur', 'change']
					},
					'formData.imgList1': {
						type: 'array',
						required: true,
						message: '请上传行驶证照片',
						trigger: ['blur', 'change']
					},
					'formData.imgList2': [
						{
							type: 'array',
							required: true,
							message: '请上传身份证正反面',
							trigger: ['blur', 'change']
						},
						{
							type: 'array',
							validator: (rule, value, callback) => {
								if (value.length <= 1) {
									return false
								} else {
									return true
								}
							},
							message: '请上传正反面',
							trigger: ['blur','change']
						}
					],
				},
				timer: null
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		onLoad(e) {

		},
		created() {
			let {phoneNumber,userName} = JSON.parse(uni.getStorageSync('userServerInfo'))
			this.model.formData.phone = phoneNumber
			this.model.formData.name = userName
			this.getOperatorList()
		},
		beforeDestroy() {
			this.timer = null
		},
		methods: {
			async getOperatorList() {
				let params = {
					status: 0
				}
				let res = await agriculturalApi.queryOperator(params)
				if(res.code === 200) {
					this.operatorList = res.data
				}
			},
			async getOrganization(no) {
				let res = await API.queryOrganization({serviceProviderNo: no,auditStatus: 1})
				if(res.code === 200) {
					this.organizationList = res.data
				}
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			// 0.选择运营方
			selectOperatorClose() {
				this.$refs.form.validateField('formData.operatorName')
			},
			selectOperator(e) {
				this.model.formData.operatorName = this.operatorList[e.detail.value].name
				this.model.formData.serviceProviderNo = this.operatorList[e.detail.value].serviceProviderNo
				this.getOrganization(this.model.formData.serviceProviderNo)
				this.$refs.form.validateField('formData.operatorName')
			},
			// 0.1选择服务方
			selectOrganizationClose() {
				this.$refs.form.validateField('formData.organizationName')
			},
			selectOrganization(e) {
				console.log(e.detail.value);
				this.model.formData.organizationName = this.organizationList[e.detail.value].name
				this.model.formData.organizationNo = this.organizationList[e.detail.value].organizationNo
				this.$refs.form.validateField('formData.organizationName')
			},
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
				this.model.formData.imgList.splice(event.index, 1)
				this.$refs.form.validateField('formData.imgList')
			},
			deletePic1(event) {
				this.fileList1.splice(event.index, 1)
				this.model.formData.imgList1.splice(event.index, 1)
				this.$refs.form.validateField('formData.imgList1')
			},
			deletePic2(event) {
				this.fileList2.splice(event.index, 1)
				this.model.formData.imgList2.splice(event.index, 1)
				this.$refs.form.validateField('formData.imgList2')
			},
			// 驾驶证
			async afterRead(event) {
				this.type = 'image'
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: `${socializedBaseurl}${result.slice(1)}`
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: agrServiceUrl + `common/file/upDown/getUploadUrl?moduleType=XG_ORGANIZATION&upDownType=FTP`,
						filePath: url,
						name: 'file',
						header: {
							'token': uni.getStorageSync("satoken") || ''
						},
						formData: {},
						success: async (res) => {
							const dataObj = JSON.parse(res.data);
							const data = dataObj.data;
							console.log(data, 'ww');
							resolve(data);
							if (this.type == 'image') {
								this.model.formData.imgList.push({
									imgId: data.slice(33),
									imgUrl: `${socializedBaseurl}${data.slice(1)}`
								})
								this.$refs.form.validateField('formData.imgList')
							} else if (this.type == 'image1') {
								this.model.formData.imgList1.push({
									imgId: data.slice(33),
									imgUrl: `${socializedBaseurl}${data.slice(1)}`
								})
								this.$refs.form.validateField('formData.imgList1')
							} else if (this.type === 'image2') {
								this.model.formData.imgList2.push({
									imgId: data.slice(33),
									imgUrl: `${socializedBaseurl}${data.slice(1)}`
								})
								this.$refs.form.validateField('formData.imgList2')
							}
						},
						fail: () => {
							uni.showToast({
								title: '图片上传失败',
								icon: 'error'
							})
						}
					});
				})
			},
			// 行驶证
			async afterRead1(event) {
				this.type = 'image1'
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList1.length
				lists.map((item) => {
					this.fileList1.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList1[fileListLen]
					this.fileList1.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: `${socializedBaseurl}${result.slice(1)}`
					}))
					fileListLen++
				}
			},
			// 身份证
			async afterRead2(event) {
				this.type = 'image2'
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList2.length
				lists.map((item) => {
					this.fileList2.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList2[fileListLen]
					this.fileList2.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: `${socializedBaseurl}${result.slice(1)}`
					}))
					fileListLen++
				}
			},
			// 申请入驻
			application() {
				this.$refs.form.validate().then(async () => {
					console.log("提交表单信息:" ,this.model.formData)
					let params = {
						...this.model.formData
					}
					delete params.operatorName
					delete params.organizationName
					delete params.imgList
					delete params.imgList1
					delete params.imgList2
					// 驾驶证照片
					if(this.model.formData.imgList.length>0) params.driveLicense = this.model.formData.imgList[0].imgUrl
					// 行驶证照片
					if(this.model.formData.imgList1.length>0) params.drivingLicense = this.model.formData.imgList1[0].imgUrl
					// 身份证
					if(this.model.formData.imgList2.length == 2) {
						params['frontIdcard'] = this.model.formData.imgList2[0].imgUrl
						params['backIdcard'] = this.model.formData.imgList2[1].imgUrl
					}
					// console.log(params); return
					let res = await API.mechanistApplication(params)
					if (res.code === 200) {
						uni.showToast({
							title: '农机手申请成功',
							icon: 'success'
						})
						this.timer = setTimeout(()=>{
							uni.reLaunch({
								url: '/pages/socialized-service/person-message/person-message'
							})
						},500)
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none"
						})
					}
				}).catch(errors => {
					console.log("失败信息:" + JSON.stringify(errors))
				})
			},
			back() {
				uni.reLaunch({
					url: '/pages/socialized-service/person-message/person-message'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	/deep/.u-form {
		padding: 0 32rpx !important;
	}

	/deep/.u-form-item {
		position: relative;
		background-color: #fff;
		margin-top: 20rpx;
		border-radius: 20rpx;
	}

	/deep/.u-form-item {
		&:nth-child(n+6) {
			background-color: #E2E7F8;
		}
	}

	// /deep/ .u-form-item__body__right__message {
	// 	margin-left: 0!important;
	// }

	.left-image {
		position: absolute;
		// top: 50%;
		// transform: translateY(-50%);
		left: 0;
		width: 54rpx;
		height: 54rpx;
		border-radius: 50%;
		margin-left: 22rpx;
		display: flex;
		justify-content: center;
		align-content: center;
		flex-wrap: wrap;
	}

	.left-img {
		height: 26rpx;
	}

	.uni-input-input {
		pointer-events: none;
	}

	/deep/ .u-form-item__body__left {
		width: 200rpx !important;
		margin-left: 50px;
	}

	.blank {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;
		align-items: center;
		justify-content: center;

		image {
			width: 104rpx;
			height: 114rpx;
		}

		.title {
			padding: 0 96rpx;
			padding-top: 38rpx;
			font-size: 32rpx
		}
	}

	/deep/ .u-icon--right {
			position: absolute;
			right: 0;
			top: 50%;
			transform: translateY(-50%);
		}

	.submit {
		margin-top: 30rpx;
		// position: absolute;
		// bottom: 150rpx;
		// left: 50%;
		// transform: translateX(-50%);

		.submit-btn {
			width: 340rpx;
			height: 60rpx;
			line-height: 60rpx;
			background: linear-gradient(270deg, #88ACFF 0%, #2165FF 100%);
			border-radius: 56rpx 56rpx 56rpx 56rpx;
			font-size: 28rpx;
			color: #FFFFFF;
			display: flex;
			justify-content: center;
			align-items: center;

			.icon-submit {
				margin-right: 10rpx;
			}
		}
	}

	/deep/ .u-upload__wrap {
		display: flex;
		align-items: center;
	}
	
	/deep/ .u-upload__deletable__icon {
		top: 12rpx;
		right: 2rpx;
		transform: scale(1.7);
	}
	.uploadBtns {
		display: flex;
	}
</style>